<?php
/*
 * @Description    : 
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2022-05-08 15:24:18
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-05-15 17:24:16
 */
// 应用公共文件

use app\common\model\FxMoney;
use app\common\model\Manager;
use app\common\RedisCache;
use app\common\service\QlRedis;
use app\lib\exception\ApiException;
use app\lib\Result;
use think\facade\Db;
use think\facade\Request;
use Yurun\Util\HttpRequest;
// 应用公共文件
function limitResult($field = '', $userid = 0, $limit = 5)
{
    $redis = new QlRedis();
    if ($redis->ttl($field . '_' . $userid) === -1) {
        $redis->del($field . '_' . $userid);
    }
    if ($redis->exists($field . '_' . $userid)) {
        $errcount = $redis->get($field . '_' . $userid);
        if ($errcount >= $limit) {
            return ['code' => -1, 'data' => '', 'msg' => '您输入密码错误次数过多或验证失败次数过多，已被临时冻结，请于2小时后重试'];
        } else {
            $redis->incr($field . '_' . $userid);
            return ['code' => 200, 'data' => '', 'msg' => '本次请求失败'];
        }
    } else {
        $redis->set($field . '_' . $userid, 1, 7200);
        return ['code' => 200, 'data' => '', 'msg' => '本次请求失败'];
    }
}
function allowCORS()
{
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    header('Access-Control-Allow-Headers:Access-Token, access-token, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
    header('Access-Control-Allow-Credentials: true');
    header("Content-type:application/json;chartset=uft-8");
    if (Request::isOptions()) {
        echo 'success';
        exit;
    }
}
function transferCheck($data, $user)
{
    // 校验用户名
    if ($data['username'] == $user['username']) {
        throw new ApiException('不能转移给自己，转移失败');
    }
    $inputPwd = md5($data['password'] . $user['salt']);
    if ($inputPwd != $user['password']
    ) {
        return Result::Error('密码不正确，请输入当前账号的登录密码');
    }
    $hasUser = Manager::field('id,status,version,version_end_time,username')->where('username', $data['username'])->find();
    if (empty($hasUser)) {
        throw new ApiException('您输入的用户名不存在，转移失败');
    }
    if ($hasUser['status'] != 1) {
        throw new ApiException($data['username'] . ' 账号状态异常，转移失败');
    }
    if ($hasUser['version_end_time'] <= time()) {
        $hasUser['version'] = 1;
    }
    $hasCode = Db::connect('mongodb')->name('sys_transfer_code')->where(['_id' => $data['transfer_code']])->find();
    if (empty($hasCode)) {
        throw new ApiException('转移码不存在，转移失败');
    }
    if (isset($hasCode['project_id']) && !empty($hasCode['project_id'])) {
        throw new ApiException('该转移码已使用，转移失败');
    }
    return $hasUser;
}
function insertRechargeOrder($txData)
{
    $txData['_id'] = (isset($txData['_id']) && !empty($txData['_id']))? $txData['_id']:createId();
    $txData['create_time'] = time();
    $txData['success_time'] = 0;
    $txData['status'] = 0;
    $txData['invoice_status'] = 0;
    Db::connect('mongodb')->name('recharge_order')->insert($txData);
}
function create_invite_code()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d')
        . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 6;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    );
    return $d;
}
function addoplog($data = [])
{
    if (!empty($data)) {
        if (!isset($data['is_admin']) || empty($data['is_admin'])) {
            $data['is_admin'] = 0;
        }
        if (!isset($data['opstatus']) || empty($data['opstatus'])) {
            $data['opstatus'] = 0;
        }
        $data['time'] = time();
        $data['_id'] = 'OL' . $data['time'] . random_int(10000000, 99999999);
        $data['ip'] = get_client_ip();
        if (config('app.mongodb.hostname') != '') {
            Db::connect('mongodb')->name('operatelog')->insert($data);
        }
    }
}
function mongodb()
{
    $client = new MongoDB\Client('mongodb://root:Dragon8798520@main-mongodb.mongodb.rds.aliyuncs.com:3717,sec-mongodb.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-29666173');
    return $client->kaifazhe;
}
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * @return string
 */
function contractFee($id,$fee,$title,$uid=0)
{
    $app = app('http')->getName();
    $apiUrl = $app . '/' . Request::controller() . '/' . Request::action();
    $data['_id'] = createId();
    $data['contract_id'] = $id;
    $data['dev_id'] = $uid;
    $data['title'] = $title.':'. $apiUrl;
    $data['fee'] = floatval($fee);
    $data['date'] = date('Y-m-d H:i:s');
    Db::connect('mongodb')->name('contract_fee_tj')->insert($data);
}
function checkphone($str)
{
    $pattern = '/^1[356789]{1}\d{9}$/';
    if (preg_match($pattern, $str)) {
        return true;
    } else {
        return false;
    }
}
function checktel($str)
{
    $isTel = '/^([0-9]{3,4}-)?[0-9]{7,8}$/';
    if (preg_match($isTel, $str)) {
        return true;
    } else {
        return false;
    }
}
function make_salt($length = 7)
{
    $chars = array(
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
        'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
        '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
        '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
        '.', ';', ':', '/', '?', '|'
    );
    $keys = array_rand($chars, $length);
    $user_salt = '';
    for ($i = 0; $i < $length; $i++) {
        $user_salt .= $chars[$keys[$i]];
    }
    return $user_salt;
}
function code62($x)
{
    $show = '';
    while ($x > 0) {
        $s = $x % 62;
        if ($s > 35) {
            $s = chr($s + 61);
        } elseif ($s > 9 && $s <= 35) {
            $s = chr($s + 55);
        }
        $show .= $s;
        $x = floor($x / 62);
    }
    return $show;
}
function make_short_id($url)
{
    $url = crc32($url);
    $result = sprintf("%u", $url);
    return code62($result);
}
function createId($prefix = '')
{
    return (new \Qianlong\SnowFlake\SnowFlake)->createId($prefix);
}
function think_encrypt($data, $key = '', $expire = 0)
{
    $key  = md5(empty($key) ? config('app.SYS_STATIC.pass_salt') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time() : 0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    $str = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
    return strtoupper(md5($str)) . $str;
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key 加密密钥
 * @return string
 */
function think_decrypt($data, $key = '')
{
    $key  = md5(empty($key) ? config('app.SYS_STATIC.pass_salt') : $key);
    $data = substr($data, 32);
    $data = str_replace(array('-', '_'), array('+', '/'), $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data   = substr($data, 10);

    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
function getWxQrcode($scene, $http = null)
{
    $apiUrl = 'https://21ds.cn/mpWeixinApi/getQrcode';
    $postData['scene_str'] = $scene;
    $postData['action_name'] = 'QR_STR_SCENE';
    $postData['expire_seconds'] = 120;
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['mw_id'] = 'MW4754391651808828';
    $info = (new RedisCache)::getMpWxInfo($postData['mw_id']);
    $postData['sign'] = devSignGeneral($postData, $info['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function getArtList($id,$page,$pageSize, $secret_key)
{
    $apiUrl = 'https://21ds.cn/article/list';
    $postData['id'] = $id;
    $postData['page'] = $page;
    $postData['pageSize'] = $pageSize;
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['sign'] = devSignGeneral($postData, $secret_key);
    $http = new \Yurun\Util\HttpRequest;
    $response = $http->get($apiUrl, $postData);
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function checkIsHasInviter($uid)
{
    $info = (new RedisCache)->getSetInviterUid($uid);
    if (!empty($info)) {
        $info = json_decode($info, true);
        if (!empty($info)) {
            $time = time();
            $txData['_id'] = createId();
            $txData['uid'] = $info['inviter_uid'];
            $txData['create_time'] = $time;
            $txData['title'] = '邀请用户注册并激活';
            $txData['type'] = '+';
            $txData['inv_username'] = $info['username'];
            $txData['pay_money'] = 0;
            $txData['status'] = 1;
            $txData['money'] = $info['money'];
            Db::connect('mongodb')->name('invite_order')->insert($txData);
            FxMoney::where('uid', $uid)->inc('ky_money', $info['money'])->update();
            Manager::where('id', $uid)->update(['invite_status' => 3]);
        }
    }
}
function contractSignerLog($sign_id,$contract_id,$contract_title,$use_tips,$uid=0, $username='', $sign_resource=1)
{
    $time = time();
    $txData['_id'] = createId();
    $txData['sign_id'] = $sign_id;
    $txData['uid'] = $uid;
    $txData['username'] = $username;
    $txData['contract_id'] = $contract_id;
    $txData['contract_title'] = $contract_title;
    $txData['sign_resource'] = intval($sign_resource);
    $txData['use_time'] = $time;
    $txData['use_tips'] = $use_tips;
    $txData['use_ip'] = get_client_ip();
    Db::connect('mongodb')->name('contract_sign_log')->insert($txData);
}
function InviterFxMoney($title, $inviter_uid, $pay_money, $money, $username, $type)
{
    if (!empty($title) && !empty($inviter_uid) && !empty($pay_money) && !empty($money) && !empty($type) && !empty($username)) {
        $time = time();
        $txData['_id'] = createId();
        $txData['uid'] = $inviter_uid;
        $txData['create_time'] = $time;
        $txData['title'] = $title;
        $txData['type'] = $type;
        $txData['inv_username'] = $username;
        $txData['pay_money'] = $pay_money;
        $txData['status'] = 1;
        $txData['money'] = $money;
        Db::connect('mongodb')->name('invite_order')->insert($txData);
        if ($type == '+') {
            FxMoney::where('uid', $inviter_uid)->inc('ky_money', $money)->update();
        } else {
            FxMoney::where('uid', $inviter_uid)->dec('ky_money', $money)->update();
        }
    }
}
function sendTemplateMsgLY($touser, $template_id, $data, $http = null)
{
    $apiUrl = 'https://21ds.cn/mpWeixinApi/sendTemplateMsg';
    $postData['touser'] = $touser;
    $postData['template_id'] = $template_id;
    $postData['data'] = $data;
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['mw_id'] = 'MW4754391651808828';
    $info = (new RedisCache)::getMpWxInfo($postData['mw_id']);
    $postData['sign'] = devSignGeneral($postData, $info['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function sendTKfMsg($touser, $msg_type, $data, $http = null)
{
    $apiUrl = 'https://21ds.cn/mpWeixinApi/sendKfMsg';
    $postData['touser'] = $touser;
    $postData['msg_type'] = $msg_type;
    $postData['data'] = $data;
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['mw_id'] = 'MW4754391651808828';
    $info = (new RedisCache)::getMpWxInfo($postData['mw_id']);
    $postData['sign'] = devSignGeneral($postData, $info['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    return $response->body();
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function getWxAccessToken($mw_id, $uid, $http = null)
{
    $apiUrl = 'https://21ds.cn/mpWeixinApi/getAccessToken';
    if (empty($uid)) {
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    } else {
        $userInfo = (new RedisCache())->getUserSetting($uid);
        $postData['dev_key'] = $userInfo['dev_key'];
    }
    $postData['mw_id'] = $mw_id;
    $info = (new RedisCache)::getMpWxInfo($mw_id);
    $postData['sign'] = devSignGeneral($postData, $info['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->get($apiUrl, $postData);
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function socketServerPush($ws_id, $room, $message, $uid, $union_id = '', $http = null)
{
    $apiUrl = 'https://21ds.cn/socket/server_push';
    if (empty($uid)) {
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    } else {
        $userInfo = (new RedisCache())->getUserSetting($uid);
        $postData['dev_key'] = $userInfo['dev_key'];
    }
    $postData['ws_id'] = $ws_id;
    $postData['room'] = $room;
    $postData['union_id'] = $union_id;
    $postData['message'] = $message;
    $info = (new RedisCache)::getWsServer($ws_id);
    $postData['sign'] = devSignGeneral($postData, $info['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    $result = json_decode($response->body(), true);
    if ($result['code'] == 200) {
        return $result['data'];
    }
    return [];
}
function doSendEmail($emaildata, $http = null)
{
    $apiUrl = 'https://21ds.cn/email/send';
    $postData['email'] = $emaildata['email'];
    $postData['content'] = $emaildata['content'];
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['es_id'] = (isset($emaildata['es_id']) && !empty($emaildata['es_id'])) ? $emaildata['es_id'] : 'ES-4817058244179833';
    $postData['title'] = (isset($emaildata['title']) && !empty($emaildata['title'])) ? $emaildata['title'] : '邮件通知';
    if (isset($emaildata['esl_id']) && !empty($emaildata['esl_id'])) {
        $postData['esl_id'] = $emaildata['esl_id'];
    }
    if (isset($emaildata['et_id']) && !empty($emaildata['et_id'])) {
        $postData['et_id'] = $emaildata['et_id'];
    }
    if (isset($emaildata['attachment']) && !empty($emaildata['attachment'])) {
        $postData['attachment'] = $emaildata['attachment'];
    }
    if (isset($emaildata['ext-1']) && !empty($emaildata['ext-1'])) {
        $postData['ext-1'] = $emaildata['ext-1'];
    }
    if (isset($emaildata['ext-2']) && !empty($emaildata['ext-2'])) {
        $postData['ext-2'] = $emaildata['ext-2'];
    }
    if (isset($emaildata['ext-3']) && !empty($emaildata['ext-3'])) {
        $postData['ext-3'] = $emaildata['ext-3'];
    }
    if (isset($emaildata['ext-4']) && !empty($emaildata['ext-4'])) {
        $postData['ext-4'] = $emaildata['ext-4'];
    }
    if (isset($emaildata['ext-5']) && !empty($emaildata['ext-5'])) {
        $postData['ext-5'] = $emaildata['ext-5'];
    }
    if (isset($emaildata['ext-6']) && !empty($emaildata['ext-6'])) {
        $postData['ext-6'] = $emaildata['ext-6'];
    }
    if (isset($emaildata['ext-7']) && !empty($emaildata['ext-7'])) {
        $postData['ext-7'] = $emaildata['ext-7'];
    }
    if (isset($emaildata['ext-8']) && !empty($emaildata['ext-8'])) {
        $postData['ext-8'] = $emaildata['ext-8'];
    }
    if (isset($emaildata['ext-9']) && !empty($emaildata['ext-9'])) {
        $postData['ext-9'] = $emaildata['ext-9'];
    }
    if (isset($emaildata['ext-10']) && !empty($emaildata['ext-10'])) {
        $postData['ext-10'] = $emaildata['ext-10'];
    }
    $serverInfo = (new RedisCache())::getEmailServerInfo($postData['es_id']);
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    if (!$http) {
        $http = new HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function doSendSms($smsData, $http = null)
{
    $apiUrl = 'https://21ds.cn/sms/send';
    $postData['params_json'] = (isset($smsData['params_json']) && !empty($smsData['params_json'])) ? $smsData['params_json'] : json_encode([]);
    $postData['st_id'] = $smsData['st_id'];
    $postData['phone'] = $smsData['phone'];
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['ss_id'] = (isset($smsData['ss_id']) && !empty($smsData['ss_id'])) ? $smsData['ss_id'] : 'SS-4823425885480948';
    $postData['ssl_id'] = (isset($smsData['ssl_id']) && !empty($smsData['ssl_id'])) ? $smsData['ssl_id'] : '';
    $postData['voice_test'] = (isset($smsData['voice_test']) && !empty($smsData['voice_test'])) ? $smsData['voice_test'] : 0;
    $serverInfo = (new RedisCache())::getSmsServerInfo($postData['ss_id']);
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    if (!$http) {
        $http = new HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function lightKeyword($content, $keyword, $length)
{
    $keyPos = mb_strpos($content, $keyword);
    if ($keyPos === false) {
        return mb_substr($content, 0, $length);
    }
    $halfLimit = intval($length / 2);
    $keywordLength = mb_strlen($keyword);
    $contentLength = mb_strlen($content);
    // Calculate start and end positions
    $startPos = max(0, $keyPos - $halfLimit);
    $endPos = $startPos + $length;
    if ($endPos > $contentLength) {
        $endPos = $contentLength;
        $startPos = max(0, $endPos - $length);
    }
    $start = mb_substr($content, $startPos, $keyPos - $startPos);
    $end = mb_substr($content, $keyPos + $keywordLength, $endPos - $keyPos - $keywordLength);
    $highlightedKeyword = '<em style="background-color: rgba(255, 170, 0, 0.34);border: 1px solid rgb(255, 170, 0);">' . $keyword . '</em>';
    return $start . $highlightedKeyword . $end;
}
function doSendPush($smsData, $http = null, $uid = 0)
{
    $apiUrl = 'https://21ds.cn/push/send';
    $postData['click_type_content'] = (isset($smsData['click_type_content']) && !empty($smsData['click_type_content'])) ? $smsData['click_type_content'] : json_encode([]);
    $postData['click_type'] = (isset($smsData['click_type']) && !empty($smsData['click_type'])) ? $smsData['click_type'] : '';
    $postData['msg_type'] = (isset($smsData['msg_type']) && !empty($smsData['msg_type'])) ? $smsData['msg_type'] : '';
    $postData['msg_content'] = (isset($smsData['msg_content']) && !empty($smsData['msg_content'])) ? $smsData['msg_content'] : '';
    $postData['channel_level'] = (isset($smsData['channel_level']) && !empty($smsData['channel_level'])) ? $smsData['channel_level'] : '';
    $postData['atMobiles'] = (isset($smsData['atMobiles']) && !empty($smsData['atMobiles'])) ? $smsData['atMobiles'] : '';
    $postData['params_json'] = (isset($smsData['params_json']) && !empty($smsData['params_json'])) ? $smsData['params_json'] : '';
    $postData['template_data'] = (isset($smsData['template_data']) && !empty($smsData['template_data'])) ? $smsData['template_data'] : '';
    $postData['template_miniprogram'] = (isset($smsData['template_miniprogram']) && !empty($smsData['template_miniprogram'])) ? $smsData['template_miniprogram'] : '';
    $postData['template_url'] = (isset($smsData['template_url']) && !empty($smsData['template_url'])) ? $smsData['template_url'] : '';
    $postData['template_touser'] = (isset($smsData['template_touser']) && !empty($smsData['template_touser'])) ? $smsData['template_touser'] : '';
    $postData['template_id'] = (isset($smsData['template_id']) && !empty($smsData['template_id'])) ? $smsData['template_id'] : '';
    $postData['title'] = $smsData['title'];
    $postData['content'] = $smsData['content'];
    $postData['cid'] = (isset($smsData['cid']) && !empty($smsData['cid'])) ? $smsData['cid'] : '';
    if (empty($uid)) {
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    } else {
        $userInfo = (new RedisCache())->getUserSetting($uid);
        $postData['dev_key'] = $userInfo['dev_key'];
    }
    $postData['ps_id'] = (isset($smsData['ps_id']) && !empty($smsData['ps_id'])) ? $smsData['ps_id'] : 'PS-4825470945110373';
    $postData['psl_id'] = (isset($smsData['psl_id']) && !empty($smsData['psl_id'])) ? $smsData['psl_id'] : '';
    $postData['platform'] = (isset($smsData['platform']) && !empty($smsData['platform'])) ? $smsData['platform'] : '';
    $serverInfo = (new RedisCache())::getPushServerInfo($postData['ps_id']);
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    if (!$http) {
        $http = new HttpRequest;
    }
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function doFileUpload($file, $fs_id = null, $fc_id = null, $http = null, $hash_file = '', $dev_key = '')
{
    if (!$http) {
        $http = new HttpRequest;
    }
    $apiUrl = 'https://21ds.cn/file/upload';
    $postData['fs_id'] = $fs_id;
    $postData['fc_id'] = $fc_id;
    if ($fc_id == 'FC4901539840376723') {
        $userInfo = (new RedisCache())->getUserSetting(1);
        $postData['dev_key'] = $userInfo['dev_key'];
    } else {
        $postData['dev_key'] = $dev_key;
    }
    $postData['hash_file'] = $hash_file;
    $serverInfo = (new RedisCache())::getFileServerInfo($postData['fs_id']);
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    $postData['file'] = $file;
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function javaApi($api,$file)
{
    $http = new HttpRequest;
    $apiUrl = 'http://ldp.java.api-internal.21ds.cn/'.$api;
    $postData['file'] = $file;
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function javaApiRequest($api,$data=null,$method='get',$type='json')
{
    $http = new HttpRequest;
    $apiUrl = 'http://ldp.java.api-internal.21ds.cn/'.$api;
    if ($method == 'get') {
        $response = $http->get($apiUrl, $data);
    }else{
        $response = $http->post($apiUrl, $data);
    }
    if ($type == 'json') {
       return json_decode($response->body(), true);
    }else{
        return $response->body();
    }
}
function doScheduleSave($postData, $uid)
{
    $postData['cate'] = isset($postData['cate']) ? $postData['cate'] : '4933803295492671';
    $postData['desc'] = isset($postData['desc']) ? $postData['desc'] : '';
    $postData['color'] = isset($postData['color']) ? $postData['color'] : '';
    $postData['ps_id'] = isset($postData['ps_id']) ? $postData['ps_id'] : '';
    $postData['loop_type'] = isset($postData['loop_type']) ? $postData['loop_type'] : '';
    $postData['end_time'] = isset($postData['end_time']) ? $postData['end_time'] : '';
    $postData['start_time'] = isset($postData['start_time']) ? $postData['start_time'] : '';
    $postData['end_date'] = isset($postData['end_date']) ? $postData['end_date'] : '';
    $postData['start_date'] = isset($postData['start_date']) ? $postData['start_date'] : '';
    $postData['date_type'] = isset($postData['date_type']) ? $postData['date_type'] : 'gl';
    $postData['before_num'] = isset($postData['before_num']) ? $postData['before_num'] : 0;
    $postData['is_force'] = isset($postData['is_force']) ? $postData['is_force'] : 0;
    $postData['loop_num'] = isset($postData['loop_num']) ? $postData['loop_num'] : 0;
    $postData['is_loop'] = isset($postData['is_loop']) ? $postData['is_loop'] : 0;
    $postData['notice_open'] = isset($postData['notice_open']) ? $postData['notice_open'] : 0;
    $postData['importance'] = isset($postData['importance']) ? $postData['importance'] : 'di';
    $http = new HttpRequest;
    $apiUrl = 'https://21ds.cn/schedule/save';
    $userInfo = (new RedisCache())->getUserSetting($uid);
    $postData['dev_key'] = $userInfo['dev_key'];
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function getAk($ak_id)
{
    $redis = new QlRedis();
    $field = 'ak:' . $ak_id;
    if ($redis->ttl($field) === -1) {
        $redis->del($field);
    }
    if ($redis->exists($field)) {
        $data = $redis->get($field);
        return json_decode($data, true);
    } else {
        $http = new HttpRequest;
        $apiUrl = 'https://21ds.cn/platform/ak';
        $postData['ak_id'] = $ak_id;
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
        $response = $http->post($apiUrl, $postData);
        $result = json_decode($response->body(), true);
        if ($result['code'] == 200) {
            $data = $result['data'];
            $redis->set($field, json_encode($data), 7200);
        } else {
            throw new ApiException('AK获取失败-' . $result['msg']);
        }
        return $data;
    }
}
function checkIsTry($type){
    if ($type == 0) {
        throw new ApiException('当前账号为体验账号，不允许执行此操作');
    }
}
function dataTuomin($string, $start = 0, $length = 0, $re = '*')
{
    if (empty($string)) {
        return false;
    }
    $strarr = array();
    $mb_strlen = mb_strlen($string);
    while ($mb_strlen) { //循环把字符串变为数组
        $strarr[] = mb_substr($string, 0, 1, 'utf8');
        $string = mb_substr($string, 1, $mb_strlen, 'utf8');
        $mb_strlen = mb_strlen($string);
    }
    $strlen = count($strarr);
    $begin = $start >= 0 ? $start : ($strlen - abs($start));
    $end = $last = $strlen - 1;
    if ($length > 0) {
        $end = $begin + $length - 1;
    } elseif ($length < 0) {
        $end -= abs($length);
    }
    for ($i = $begin; $i <= $end; $i++) {
        $strarr[$i] = $re;
    }
    if ($begin >= $end || $begin >= $last || $end > $last) return false;
    return implode('', $strarr);
}
function deleteFile($file_id, $fs_id, $uid = 0, $http = null, $file_url = '')
{
    if (!$http) {
        $http = new HttpRequest;
    }
    $apiUrl = 'https://21ds.cn/file/deleteFile';
    $postData['file_id'] = (is_array($file_id)) ? implode(',', $file_id) : $file_id;
    $postData['file_url'] = (is_array($file_url)) ? implode(',', $file_url) : $file_url;
    $postData['fs_id'] = $fs_id;
    if (empty($uid)) {
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    } else {
        $userInfo = (new RedisCache())->getUserSetting($uid);
        $postData['dev_key'] = $userInfo['dev_key'];
    }
    $serverInfo = (new RedisCache())::getFileServerInfo($fs_id);
    $postData['remote_ip'] = get_client_ip();
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function doLogPush($postData, $http = null, $isLog = false)
{
    if (!isset($postData['lsi_id']) || empty($postData['lsi_id'])) {
        $postData['lsi_id'] = 'LSI-4841802831946282';
    }
    $serverInfo = (new RedisCache())::getLogSiteInfo($postData['lsi_id']);
    $postData['remote_ip'] = get_client_ip();
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    if (!$http) {
        $http = new \Yurun\Util\HttpRequest;
    }
    $response = $http->post('https://21ds.cn/log/push', $postData);
    if ($isLog) {
        return true;
    }
    return json_decode($response->body(), true);
}
function uploadFileJm($file, $fs_id, $fc_id, $hash_file = '', $dev_key = '')
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/file/upload';
    $postData['fs_id'] = $fs_id;
    $postData['fc_id'] = $fc_id;
    if (empty($dev_key)) {
        $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    } else {
        if (is_numeric($dev_key)) {
            $userInfo = (new RedisCache())->getUserSetting($dev_key);
            $postData['dev_key'] = $userInfo['dev_key'];
        } else {
            $postData['dev_key'] = $dev_key;
        }
    }
    $serverInfo = (new RedisCache())::getFileServerInfo($fs_id);
    $postData['hash_file'] = $hash_file;
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    $postData['file'] = $file;
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function contentEncrypt($data, $key = '', $iv = '')
{
    $key_id = '';
    if (empty($key) && empty($iv)) {
        $keyCount = Db::name('AesKey')->where('status', 1)->count();
        $id = random_int(1, $keyCount);
        $keyInfo = Db::name('AesKey')->where('id', $id)->find();
        $key = $keyInfo['key'];
        $iv = $keyInfo['iv'];
        $key_id = $keyInfo['id'];
    }
    $return['content'] = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    $return['key_id'] = $key_id;
    return $return;
}

function contentDecrypt($data, $key_id)
{
    $keyInfo = Db::name('AesKey')->where('id', $key_id)->find();
    $key = $keyInfo['key'];
    $iv = $keyInfo['iv'];
    return openssl_decrypt($data, 'aes-256-cbc', $key, 0, $iv);
}
function deleteFileJm($file_id)
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/file/deleteFile';
    $postData['file_id'] = (is_array($file_id)) ? implode(',', $file_id) : $file_id;
    $postData['fs_id'] = 'FS4904016609543243';
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['remote_ip'] = get_client_ip();
    $postData['sign'] = devSignGeneral($postData, 'Xi42b8E2RQCQBBGFMxmW7hRPXK2GnyTXKix36TdsPtcGTbBFywsEe4kSi2fR2eCf');
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function uploadToContract($file, $hash_file = '')
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/file/upload';
    $postData['fs_id'] = 'FS4901539499681767';
    $postData['fc_id'] = 'FC4901539840376723';
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['hash_file'] = $hash_file;
    $postData['sign'] = devSignGeneral($postData, 'jJdx4XSQ4w775srtiw82xC7s5jfHtT5FzkHfXarMNCmCN2WdFMFFmjfbjaCpWjNs');
    $postData['file'] = $file;
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function getImgSuffix($name)
{
    $info = getimagesize($name);
    $suffix = false;
    if ($mime = $info['mime']) {
        $suffix = explode('/', $mime)[1];
    }
    return $suffix;
}
function deleteContractFile($file_id)
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/file/deleteFile';
    $postData['file_id'] = (is_array($file_id)) ? implode(',', $file_id) : $file_id;
    $postData['fs_id'] = 'FS4901539499681767';
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['remote_ip'] = get_client_ip();
    $postData['sign'] = devSignGeneral($postData, 'jJdx4XSQ4w775srtiw82xC7s5jfHtT5FzkHfXarMNCmCN2WdFMFFmjfbjaCpWjNs');
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function makeShortUrl($url, $title, $expire = 7)
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/short_url/make';
    $postData['url'] = $url;
    $postData['title'] = $title;
    $postData['expire'] = $expire;
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['sign'] = devSignGeneral($postData, 'jJdx4XSQ4w775srtiw82xC7s5jfHtT5FzkHfXarMNCmCN2WdFMFFmjfbjaCpWjNs');
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true);
}
function getContractFileUrl($file_url, $fs_id, $dev_key)
{
    $http = new \Yurun\Util\HttpRequest;
    $apiUrl = 'https://21ds.cn/file/getFileUrl';
    $postData['file_url'] = (is_array($file_url)) ? implode(',', $file_url) : $file_url;
    $postData['fs_id'] = $fs_id;
    $postData['dev_key'] = $dev_key;
    $postData['remote_ip'] = get_client_ip();
    $serverInfo = (new RedisCache())::getFileServerInfo($postData['fs_id']);
    $postData['sign'] = devSignGeneral($postData, $serverInfo['server_secret']);
    $response = $http->post($apiUrl, $postData);
    return json_decode($response->body(), true)['data'];
}
function insertContractLog($uid, $title, $contract_id, $msg, $status = 1, $jm_msg = '', $qsf = '')
{
    $contractData['_id'] = createId();
    $contractData['title'] = $title;
    $contractData['uid'] = $uid;
    $contractData['qsf'] = $qsf;
    $contractData['contract_id'] = $contract_id;
    $contractData['msg'] = $msg;
    $contractData['jm_msg'] = $jm_msg;
    $contractData['status'] = $status;
    $contractData['time'] = time();
    $contractData['ip'] = get_client_ip();
    $getUserAgentData = getUserAgentData();
    $contractData['device'] = $getUserAgentData['device'];
    $contractData['browser'] = $getUserAgentData['browser'];
    $contractData['os'] = $getUserAgentData['os'];
    Db::connect('mongodb')->name('contract_log_' . $uid)->insert($contractData);
}
function sysLogPush($postData, $http = null, $isLog = false)
{
    $postData['lsi_id'] = 'LSI-4842167657502251';
    $postData['sign'] = devSignGeneral($postData, 'Rtzj2NciXipWeQ2rm3mpcMjx8T4rSzWppQaszE26anHHnTdF6p8fwXR7keMXECk4');
    // if ($isLog) {
    //     return true;
    // }
    $response = $http->post('https://21ds.cn/log/push', $postData);
    if ($isLog) {
        return true;
    }
    return json_decode($response->body(), true);
}
function devSignGeneral($data, $secretKey)
{
    unset($data['sign']);
    // Sort the data by key
    ksort($data);
    // Convert the data to a query string
    $queryString = http_build_query($data);
    // Add the secret key to the query string
    $queryString .= $secretKey;
    // Generate the signature using the SHA256 algorithm
    $signature = hash('sha256', $queryString);
    // Return the signature
    return $signature;
}
function create_uuid($prefix = 'LDP')
{    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $prefix . $uuid;
}
function createULId($prefix = 'LDP')
{    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $prefix . $uuid;
}
function get_client_ip()
{
    $ip = 'unknown';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_ip'])) {
            $ip = $_SERVER['HTTP_CLIENT_ip'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_ip')) {
            $ip = getenv('HTTP_CLIENT_ip');
        } else {
            $ip = getenv('REMOTE_ADDR');
        }
    }
    if (trim($ip) == '::1') {
        $ip = '127.0.0.1';
    }
    return $ip;
}
function getUserAgentData()
{
    $userAgent = $_SERVER['HTTP_USER_AGENT'];

    // 获取操作系统信息
    $os = "Unknown OS";
    $osArray = array(
        '/windows nt 10/i'      =>  'Windows 10',
        '/windows nt 6.3/i'     =>  'Windows 8.1',
        '/windows nt 6.2/i'     =>  'Windows 8',
        '/windows nt 6.1/i'     =>  'Windows 7',
        '/windows nt 6.0/i'     =>  'Windows Vista',
        '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
        '/windows nt 5.1/i'     =>  'Windows XP',
        '/windows xp/i'         =>  'Windows XP',
        '/windows nt 5.0/i'     =>  'Windows 2000',
        '/windows me/i'         =>  'Windows ME',
        '/win98/i'              =>  'Windows 98',
        '/win95/i'              =>  'Windows 95',
        '/win16/i'              =>  'Windows 3.11',
        '/macintosh|mac os x/i' =>  'Mac OS X',
        '/mac_powerpc/i'        =>  'Mac OS 9',
        '/linux/i'              =>  'Linux',
        '/ubuntu/i'             =>  'Ubuntu',
        '/iphone/i'             =>  'iPhone',
        '/ipod/i'               =>  'iPod',
        '/ipad/i'               =>  'iPad',
        '/android/i'            =>  'Android',
        '/blackberry/i'         =>  'BlackBerry',
        '/webos/i'              =>  'Mobile'
    );
    foreach ($osArray as $regex => $value) {
        if (preg_match($regex, $userAgent)) {
            $os = $value;
        }
    }

    // 获取浏览器信息
    $browser = "Unknown Browser";
    $browserArray = array(
        '/msie/i'       =>  'Internet Explorer',
        '/firefox/i'    =>  'Firefox',
        '/safari/i'     =>  'Safari',
        '/chrome/i'     =>  'Chrome',
        '/edge/i'       =>  'Edge',
        '/opera/i'      =>  'Opera',
        '/netscape/i'   =>  'Netscape',
        '/maxthon/i'    =>  'Maxthon',
        '/konqueror/i'  =>  'Konqueror',
        '/mobile/i'     =>  'Handheld Browser'
    );
    foreach ($browserArray as $regex => $value) {
        if (preg_match($regex, $userAgent)) {
            $browser = $value;
        }
    }

    // 获取设备信息
    $device = 'Unknown Device';
    if (preg_match('/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i', $userAgent)) {
        $device = 'Mobile';
    } else if (preg_match('/Tablet|iPad/i', $userAgent)) {
        $device = 'Tablet';
    } else {
        $device = 'Desktop';
    }

    return [
        'device' => $device,
        'browser' => $browser,
        'os' => $os
    ];
}
